#---------------------------------------------------------------------------
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#---------------------------------------------------------------------------
#
# automake_config.py
# Desc: Wrapper around automake's './confgure' build command.
#       The 'AutomakeComponent' depends on this component.
#
import os
import shutil

from src import action
from src.component import Component
from src import filecache
from src.flags import flags
from src.registry import registry
from src.mod.file import FileComponent
from src import util


class AutomakeConfigComponent(Component):

  def Init(self, install_dir, configure_flags=None, **kwargs):
    Component.Init(self, **kwargs)

    self.install_dir = install_dir
    self.configure_flags = util.MakeArgumentList(configure_flags)
    # List of targets built by ./confgure script and required for Automake
    # TODO: Verify that this is a standard list, else make params.
    for target in self.ConvertPaths(['Makefile', 'config.status'], build_path=True):
      self.AddTarget(registry.Define(target, FileComponent))

  def ShowBuildOutputOnSuccess(self):
    # Automake normally generate lots of output.
    return flags.verbose

  def Build(self):
    shutil.rmtree(self.GetBuildDirectory())
    shutil.copytree(self.GetDirectory(), self.GetBuildDirectory())

    cmd = action.BuildCommand(action='./configure',
                              desc='configure %s' % self.GetName(),
                              work_dir=self.GetBuildDirectory())
    cmd.Add('--prefix="%s"' % util.AbsPath(self.install_dir))
    cmd.AddFlags(self.configure_flags)

    # TODO: Add optimization flags for -opt builds

    return cmd.Run()

  def Clean(self):
    # TODO: Need better way for Clean() to run multiple commands

    if os.path.isdir(self.GetBuildDirectory()):
      # 'distclean' make target cleans everything, incluing ./configure output.
      result = action.BuildCommand('make distclean',
                                    desc='cleaned %s' % self.GetName(),
                                    work_dir=self.GetBuildDirectory()).Run()

      # TODO: Check for error
      shutil.rmtree(self.GetBuildDirectory())

      return result
    else:
      return None
